<template>
  <div class="home-container">
    <el-row :gutter="15" class="home-card-one mb15">
      <el-col
          :xs="24"
          :sm="12"
          :md="12"
          :lg="6"
          :xl="6"
          v-for="(v, k) in homeOne"
          :key="k"
          :class="{ 'home-media home-media-lg': k > 1, 'home-media-sm': k === 1 }"
      >
        <div class="home-card-item flex">
          <div class="flex-margin flex w100" :class="` home-one-animation${k}`">
            <div class="flex-auto">
              <span class="font30">{{ v.num1 }}</span>
              <span class="ml5 font16" :style="{ color: v.color1 }" v-if="k<2"></span>
              <div class="mt10">{{ v.num3 }}</div>
            </div>
            <div class="home-card-item-icon flex" :style="{ background: `var(${v.color2})` }">
              <i class="flex-margin font32" :class="v.num4" :style="{ color: `var(${v.color3})` }"></i>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="15" class="home-card-two mb15">
      <el-col :xs="24" :sm="14" :md="14" :lg="16" :xl="16">
        <div class="home-card-item">
          <div style="height: 100%" ref="homeLineRef"></div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="10" :md="10" :lg="8" :xl="8" class="home-media">
        <div class="home-card-item">
          <div style="height: 100%" ref="homePieRef"></div>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="15" class="home-card-three">
      <el-col :xs="24" :sm="10" :md="10" :lg="8" :xl="8">
        <div class="home-card-item">
          <div class="home-card-item-title">机构发文量</div>
          <div class="home-monitor">
            <div class="flex-warp">
              <div class="flex-warp-item" v-for="(v, k) in homeThreee" :key="k">
                <div class="flex-warp-item-box" :class="`home-animation${k}`">
                  <div class="flex-margin">
                    <i :class="v.icon" :style="{ color: v.iconColor }"></i>
                    <span class="pl5">{{ v.label }}</span>
                    <div class="mt10">{{ v.value }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="14" :md="14" :lg="16" :xl="16" class="home-media">
        <div class="home-card-item">
          <div style="height: 100%" ref="homeBarRef"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts">
import {defineComponent, nextTick, onActivated, onMounted, reactive, ref, toRefs, watch} from 'vue';
import * as echarts from 'echarts';
import {storeToRefs} from 'pinia';
import {useThemeConfig} from '/@/stores/themeConfig';
import {useTagsViewRoutes} from '/@/stores/tagsViewRoutes';
import * as api from './api.ts'
import {getAgentList} from "/@/views/system/console/single/api";

let global: any = {
  homeChartOne: null,
  homeChartTwo: null,
  homeCharThree: null,
  dispose: [null, '', undefined],
};

// const intelliNum = ref()
// getActiveIntelliNum().then((response : any ) =>{
//   console.log("")
//   console.log(response.data)
// })

const journalCountRef = ref();
const docCountRef = ref();
const yearsRef = ref();
const activeAgentCountRef = ref();

const initData = async () => {
  // 获取历史统计信息
  api.getHistoryStatics().then((response: any) => {
    let data = response.data;
    journalCountRef.value = data.journalCount;
    docCountRef.value = data.docCount;
    yearsRef.value = `${data.minYear}-${data.maxYear}`
  })
  activeAgentCountRef.value = await getActiveAgentCount()
}

// 活跃智能体数量
async function getActiveAgentCount() {
  let allData = [] as any[];
  let currentPage = 1;
  let pageSize = 20033;

  const response = await getAgentList({pageNum: currentPage, pageSize: pageSize});
  allData = [...allData, ...response.data]; // 累加所有数据
  return allData.filter((agent: any) => agent.status === 1).length;
}

export default defineComponent({
  name: 'overview',
  setup() {
    const homeLineRef = ref();
    const homePieRef = ref();
    const homeBarRef = ref();
    const storesTagsViewRoutes = useTagsViewRoutes();
    const storesThemeConfig = useThemeConfig();
    const {themeConfig} = storeToRefs(storesThemeConfig);
    const {isTagsViewCurrenFull} = storeToRefs(storesTagsViewRoutes);
    const state = reactive({
      homeOne: [
        {
          num1: journalCountRef,
          num2: '',
          num3: '爬取期刊数量',
          num4: 'fa fa-meetup',
          color1: '#FF6462',
          color2: '--next-color-primary-lighter',
          color3: '--el-color-primary',
        },
        {
          num1: docCountRef,
          num2: '',
          num3: '爬取文献数量',
          num4: 'iconfont icon-ditu',
          color1: '#6690F9',
          color2: '--next-color-success-lighter',
          color3: '--el-color-success',
        },
        {
          num1: yearsRef,
          num2: '',
          num3: '数据年份',
          num4: 'iconfont icon-zaosheng',
          color1: '#6690F9',
          color2: '--next-color-warning-lighter',
          color3: '--el-color-warning',
        },
        {
          num1: activeAgentCountRef,
          num2: '',
          num3: '活跃智能体数量',
          num4: 'fa fa-github-alt',
          color1: '#FF6462',
          color2: '--next-color-danger-lighter',
          color3: '--el-color-danger',
        },
      ],
      homeThreee: [],
      myCharts: [],
      charts: {
        theme: '',
        bgColor: '',
        color: '#303133',
      },
    });

    const initInstitutions = async () => {
      const homeThree = [];  // 最终要返回的数据
      const institutionTotals = {};  // 存储机构发文数量汇总
      const specialInstitutions = ['中南大学', 'CSU', 'Central South University'];  // 特殊机构名

      // 逐个期刊请求数据
      for (let i = 1; i < 10; i++) {
        const periodicalId = i;
        try {
          // 获取期刊的机构发文数量
          const res = await api.getinstitutionArticleNum(periodicalId);
          const data = res.data;

          // 遍历每个年份的数据
          Object.values(data).forEach(yearData => {
            // 遍历每个机构的数据
            Object.entries(yearData).forEach(([institution, count]) => {
              if (!institutionTotals[institution]) {
                institutionTotals[institution] = 0; // 初始化该机构的发文数量
              }
              institutionTotals[institution] += count; // 累加发文数量
            });
          });
        } catch (error) {
          console.error(`期刊 ${periodicalId} 请求失败:`, error);
          // 失败时继续进行下一个期刊的请求
        }
      }

      // 将机构按发文数量降序排序
      const sortedInstitutions = Object.entries(institutionTotals)
          .sort((a, b) => b[1] - a[1]); // 按总发文数量降序排序

      // 取前九名机构
      let topNineInstitutions = sortedInstitutions.slice(0, 9);

      // 检查是否包含特殊机构
      let specialInstitutionFound = false;
      const topInstitutions = topNineInstitutions.filter(([institution, total]) => {
        // 如果机构名包含特殊机构之一，标记
        if (specialInstitutions.some(special => institution.includes(special))) {
          specialInstitutionFound = true;  // 标记为找到了特殊机构
          return false;  // 不加入前 9
        }
        return true;  // 否则正常加入前 9
      });

      // 如果找到了特殊机构，添加它到结果中
      if (specialInstitutionFound) {
        // 添加特殊机构（例如，加入中南大学）
        specialInstitutions.forEach(specialInstitution => {
          const foundInstitution = sortedInstitutions.find(([institution, total]) =>
              institution.includes(specialInstitution)
          );
          if (foundInstitution) {
            topInstitutions.push(foundInstitution);  // 添加找到的特殊机构
          }
        });
      }

      // 构建 homeThree 数据
      topInstitutions.forEach(([institution, total], index) => {
        const iconMap = [
          'icon-yangan', 'icon-wendu', 'icon-shidu', 'icon-shidu',
          'icon-zaosheng', 'icon-zaosheng', 'icon-zaosheng', 'icon-zaosheng', 'icon-zaosheng'
        ];

        const value = total;
        homeThree.push({
          icon: `iconfont ${iconMap[index]}`,  // 根据顺序选择图标
          label: institution,  // 机构名称
          value: value,  // 发文数量
          iconColor: getIconColor(index),  // 自定义图标颜色（根据 index 或其他逻辑）
        });
      });

      state.homeThreee = homeThree;
    };


// 获取图标颜色的函数（可以根据不同的 index 设定不同的颜色）
    const getIconColor = (index) => {
      const colors = [
        '#F72B3F', '#91BFF8', '#88D565', '#88D565', '#FBD4A0',
        '#FBD4A0', '#FBD4A0', '#FBD4A0', '#FBD4A0'
      ];
      return colors[index];
    };


    // 折线图
    const initLineChart = () => {
      if (!global.dispose.some((b: any) => b === global.homeChartOne)) global.homeChartOne.dispose();
      global.homeChartOne = <any>echarts.init(homeLineRef.value, state.charts.theme);
      const option = {
        backgroundColor: state.charts.bgColor,
        title: {
          text: '年度爬取进展',
          x: 'left',
          textStyle: {fontSize: '15', color: state.charts.color},
        },
        grid: {top: 70, right: 20, bottom: 30, left: 30},
        tooltip: {trigger: 'axis'},
        legend: {data: ['预定任务量', '最新爬取量'], right: 0},
        xAxis: {
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
        },
        yAxis: [
          {
            type: 'value',
            name: '数量',
            splitLine: {show: true, lineStyle: {type: 'dashed', color: '#f5f5f5'}},
          },
        ],
        series: [
          {
            name: '预定任务量',
            type: 'line',
            symbolSize: 6,
            symbol: 'circle',
            smooth: true,
            data: [0, 41.1, 30.4, 65.1, 53.3, 53.3, 53.3, 41.1, 30.4, 65.1, 53.3, 10],
            lineStyle: {color: '#fe9a8b'},
            itemStyle: {color: '#fe9a8b', borderColor: '#fe9a8b'},
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {offset: 0, color: '#fe9a8bb3'},
                {offset: 1, color: '#fe9a8b03'},
              ]),
            },
          },
          {
            name: '最新爬取量',
            type: 'line',
            symbolSize: 6,
            symbol: 'circle',
            smooth: true,
            data: [0, 24.1, 7.2, 15.5, 42.4, 42.4, 42.4, 24.1, 7.2, 15.5, 42.4, 0],
            lineStyle: {color: '#9E87FF'},
            itemStyle: {color: '#9E87FF', borderColor: '#9E87FF'},
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {offset: 0, color: '#9E87FFb3'},
                {offset: 1, color: '#9E87FF03'},
              ]),
            },
            emphasis: {
              itemStyle: {
                color: {
                  type: 'radial',
                  x: 0.5,
                  y: 0.5,
                  r: 0.5,
                  colorStops: [
                    {offset: 0, color: '#9E87FF'},
                    {offset: 0.4, color: '#9E87FF'},
                    {offset: 0.5, color: '#fff'},
                    {offset: 0.7, color: '#fff'},
                    {offset: 0.8, color: '#fff'},
                    {offset: 1, color: '#fff'},
                  ],
                },
                borderColor: '#9E87FF',
                borderWidth: 2,
              },
            },
          },
        ],
      };
      (<any>global.homeChartOne).setOption(option);
      (<any>state.myCharts).push(global.homeChartOne);
    };

    let pieValue = [];
    const initPie = () => {
      api.getTaskRatio().then((res: any) => {
        // 计算总数
        const total = res["爬取成功"] + res["爬取失败"] + res["待爬取"];
        pieValue = [(res["爬取成功"] / total * 100).toFixed(2), (res["爬取失败"] / total * 100).toFixed(2), (res["待爬取"] / total * 100).toFixed(2)];
      });
    };

    // 饼图
    const initPieChart = () => {
      initPie();
      if (!global.dispose.some((b: any) => b === global.homeChartTwo)) global.homeChartTwo.dispose();
      global.homeChartTwo = <any>echarts.init(homePieRef.value, state.charts.theme);
      var getname = ['爬取成功', '爬取失败', '待爬取'];
      var getvalue = [23.1, 35.4, 41.5];
      //var getvalue = pieValue;
      var data = [];
      for (var i = 0; i < getname.length; i++) {
        data.push({name: getname[i], value: getvalue[i]});
      }
      const colorList = ['#51A3FC', '#36C78B', '#FEC279', '#968AF5', '#E790E8'];
      const option = {
        backgroundColor: state.charts.bgColor,
        title: {
          text: '任务环比',
          x: 'left',
          textStyle: {fontSize: '15', color: state.charts.color},
        },
        tooltip: {trigger: 'item', formatter: '{b} <br/> {c}%'},
        graphic: {
          elements: [
            {
              type: 'image',
              z: -1,
              style: {
                width: 230,
                height: 230,
              },
              left: '16.5%',
              top: 'center',
            },
          ],
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: '0%',
          left: '65%',
          top: 'center',
          itemWidth: 14,
          itemHeight: 14,
          data: getname,
          textStyle: {
            rich: {
              name: {
                fontSize: 14,
                fontWeight: 400,
                width: 200,
                height: 35,
                padding: [0, 0, 0, 60],
                color: state.charts.color,
              },
              rate: {
                fontSize: 15,
                fontWeight: 500,
                height: 35,
                width: 40,
                padding: [0, 0, 0, 30],
                color: state.charts.color,
              },
            },
          },
        },
        series: [
          {
            type: 'pie',
            radius: ['82', themeConfig.value.isIsDark ? '50' : '102'],
            center: ['32%', '50%'],
            itemStyle: {
              color: function (params: any) {
                return colorList[params.dataIndex];
              },
            },
            label: {show: false},
            labelLine: {show: false},
            data: data,
          },
        ],
      };
      (<any>global.homeChartTwo).setOption(option);
      (<any>state.myCharts).push(global.homeChartTwo);
    };

    let barVolumeValue = [];
    let barYears = [];
    let barRates = [];
    const initBar = () => {
      api.getVolumeView().then((res: any) => {
            const data = res.data;
            barYears = Object.keys(data).sort();
            barVolumeValue = barYears.map(year => ({
              value: data[year],
            }));

            barRates.push({value: 0});
            for (let i = 1; i < barVolumeValue.length; i++) {
              const currentYearValue = barVolumeValue[i].value;
              const previousYearValue = barVolumeValue[i - 1].value;

              const growthRate = previousYearValue !== 0
                  ? ((currentYearValue - previousYearValue) / previousYearValue) * 100
                  : 0; // 避免除以 0 的情况

              barRates.push({
                value: growthRate.toFixed(2)
              });
            }
          }
      )
    }

    // 柱状图
    const initBarChart = () => {
      initBar();
      if (!global.dispose.some((b: any) => b === global.homeCharThree)) global.homeCharThree.dispose();
      global.homeCharThree = <any>echarts.init(homeBarRef.value, state.charts.theme);
      const option = {
        backgroundColor: state.charts.bgColor,
        title: {
          text: '近五年数据量',
          x: 'left',
          textStyle: {fontSize: '15', color: state.charts.color},
        },
        tooltip: {trigger: 'axis'},
        legend: {data: ['增长速度', '发文量'], right: 0},
        grid: {top: 70, right: 80, bottom: 30, left: 80},
        xAxis: [
          {
            type: 'category',
            data: barYears,
            boundaryGap: true,
            axisTick: {show: false},
          },
        ],
        yAxis: [
          {
            name: '增长速度',
            nameLocation: 'middle',
            nameTextStyle: {padding: [3, 4, 50, 6]},
            splitLine: {show: true, lineStyle: {type: 'dashed', color: '#f5f5f5'}},
            axisLine: {show: false},
            axisTick: {show: false},
            axisLabel: {color: state.charts.color, formatter: '{value} '},
          },
          {
            name: '发文量',
            nameLocation: 'middle',
            nameTextStyle: {padding: [50, 4, 5, 6]},
            splitLine: {show: false},
            axisLine: {show: false},
            axisTick: {show: false},
            axisLabel: {color: state.charts.color, formatter: '{value} '},
          },
        ],
        series: [
          // {
          //   name: '可以去掉',
          //   type: 'line',
          //   smooth: true,
          //   showSymbol: true,
          //   // 矢量画五角星
          //   symbol: 'path://M150 0 L80 175 L250 75 L50 75 L220 175 Z',
          //   symbolSize: 12,
          //   yAxisIndex: 0,
          //   areaStyle: {
          //     color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          //       {offset: 0, color: 'rgba(250,180,101,0.3)'},
          //       {offset: 1, color: 'rgba(250,180,101,0)'},
          //     ]),
          //     shadowColor: 'rgba(250,180,101,0.2)',
          //     shadowBlur: 20,
          //   },
          //   itemStyle: {color: '#FF8000'},
          //   // data中可以使用对象，value代表相应的值，另外可加入自定义的属性
          //   data: [
          //     {value: 1, stationName: 's1'},
          //     {value: 3, stationName: 's2'},
          //     {value: 4, stationName: 's3'},
          //     {value: 9, stationName: 's4'},
          //     {value: 3, stationName: 's5'},
          //     {value: 2, stationName: 's6'},
          //   ],
          // },
          {
            name: '增长速度',
            type: 'line',
            smooth: true,
            showSymbol: true,
            symbol: 'emptyCircle',
            symbolSize: 12,
            yAxisIndex: 0,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {offset: 0, color: 'rgba(199, 237, 250,0.5)'},
                    {offset: 1, color: 'rgba(199, 237, 250,0.2)'},
                  ],
                  false
              ),
            },
            itemStyle: {
              color: '#3bbc86',
            },
            data: barRates,
          },
          {
            name: '发文量',
            type: 'bar',
            barWidth: 30,
            yAxisIndex: 1,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {offset: 0, color: 'rgba(108,80,243,0.3)'},
                {offset: 1, color: 'rgba(108,80,243,0)'},
              ]),
              //柱状图圆角
              borderRadius: [30, 30, 0, 0],
            },
            data: barVolumeValue,
          },
        ],
      };
      (<any>global.homeCharThree).setOption(option);
      (<any>state.myCharts).push(global.homeCharThree);
    };
    // 批量设置 echarts resize
    const initEchartsResizeFun = () => {
      nextTick(() => {
        setTimeout(() => {
          // 检查 homeLineRef 是否有效
          if (homeLineRef.value && homeLineRef.value instanceof HTMLElement) {
            initLineChart();  // 初始化折线图
          } else {
            console.warn('homeLineRef is not a valid DOM element.');
          }
        }, 200);

        setTimeout(() => {
          // 检查 homePieRef 是否有效
          if (homePieRef.value && homePieRef.value instanceof HTMLElement) {
            initPieChart();  // 初始化饼图
          } else {
            console.warn('homePieRef is not a valid DOM element.');
          }
        }, 500);

        setTimeout(() => {
          // 检查 homeBarRef 是否有效
          if (homeBarRef.value && homeBarRef.value instanceof HTMLElement) {
            initBarChart();  // 初始化柱状图
          } else {
            console.warn('homeBarRef is not a valid DOM element.');
          }
        }, 700);
      });
    };

    // 批量设置 echarts resize
    const initEchartsResize = () => {
      window.addEventListener('resize', initEchartsResizeFun);
    };
    //
    // 页面加载时
    onMounted(() => {
      initEchartsResize();
      initData();
      console.log("111")
      initInstitutions();
    });
    // 由于页面缓存原因，keep-alive
    onActivated(() => {
      initEchartsResizeFun();
    });
    // 监听 vuex 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
    watch(
        () => isTagsViewCurrenFull.value,
        () => {
          initEchartsResizeFun();
        }
    );
    // 监听 vuex 中是否开启深色主题
    watch(
        () => themeConfig.value.isIsDark,
        (isIsDark) => {
          nextTick(() => {
            state.charts.theme = isIsDark ? 'dark' : '';
            state.charts.bgColor = isIsDark ? 'transparent' : '';
            state.charts.color = isIsDark ? '#dadada' : '#303133';
            setTimeout(() => {
              initLineChart();
            }, 500);
            setTimeout(() => {
              initPieChart();
            }, 700);
            setTimeout(() => {
              initBarChart();
            }, 1000);
          });
        },
        {
          deep: true,
          immediate: true,
        }
    );
    return {
      homeLineRef,
      homePieRef,
      homeBarRef,
      ...toRefs(state),
    };
  },
});
</script>

<style scoped lang="scss">
$homeNavLengh: 8;
.home-container {
  overflow: hidden;

  .home-card-one,
  .home-card-two,
  .home-card-three {
    .home-card-item {
      width: 100%;
      height: 130px;
      border-radius: 4px;
      transition: all ease 0.3s;
      padding: 20px;
      overflow: hidden;
      background: var(--el-color-white);
      color: var(--el-text-color-primary);
      border: 1px solid var(--next-border-color-light);

      &:hover {
        box-shadow: 0 2px 12px var(--next-color-dark-hover);
        transition: all ease 0.3s;
      }

      &-icon {
        width: 70px;
        height: 70px;
        border-radius: 100%;
        flex-shrink: 1;

        i {
          color: var(--el-text-color-placeholder);
        }
      }

      &-title {
        font-size: 15px;
        font-weight: bold;
        height: 30px;
      }
    }
  }

  .home-card-one {
    @for $i from 0 through 3 {
      .home-one-animation#{$i} {
        opacity: 0;
        animation-name: error-num;
        animation-duration: 0.5s;
        animation-fill-mode: forwards;
        animation-delay: calc($i/10) + s;
      }
    }
  }

  .home-card-two,
  .home-card-three {
    .home-card-item {
      height: 400px;
      width: 100%;
      overflow: hidden;

      .home-monitor {
        height: 100%;

        .flex-warp-item {
          width: 25%;
          height: 111px;
          display: flex;

          .flex-warp-item-box {
            margin: auto;
            text-align: center;
            color: var(--el-text-color-primary);
            display: flex;
            border-radius: 5px;
            background: var(--next-bg-color);
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
              background: var(--el-color-primary-light-9);
              transition: all 0.3s ease;
            }
          }

          @for $i from 0 through $homeNavLengh {
            .home-animation#{$i} {
              opacity: 0;
              animation-name: error-num;
              animation-duration: 0.5s;
              animation-fill-mode: forwards;
              animation-delay: calc($i/10) + s;
            }
          }
        }
      }
    }
  }
}
</style>
